<?php
namespace app\yue\home;

use app\index\controller\Home;
use GatewayClient\Gateway;
use think\Db;

class Common extends Home
{
    protected $refund_rate;
    protected $house_fee;
    protected $options;
    protected $appid;
    protected $secret;
    protected $rank_change_interval;

    public function _initialize()
    {
        parent::_initialize();
        $app_config                 = module_config($this->request->module());
        $account_id                 = $app_config['account_id'];
        $this->options              = Db::name('wechat_account')->find($account_id);
        $this->refund_rate          = $app_config['refund_rate'];
        $this->house_fee            = $app_config['house_fee'];
        $this->appid                = $this->options['appid'];
        $this->secret               = $this->options['appsecret'];
        $this->rank_change_interval = $app_config['rank_change_interval'] * 3600 * 24;
        Gateway::$registerAddress   = $app_config['socket_address'];
    }

    public function index()
    {

        $items = Db::view('yue_member', 'id')
            ->view('yue_round_member', 'id', 'yue_member.id = yue_round_member.uid')
            ->where(['yue_round_member.rid' => 2830])
            ->order('yue_member.rank, yue_member.score')
            ->select();

        $mode   = count($items) / 2;
        $list[] = ['id' => array_slice($items, $mode - 1, 1)[0]['id'], 'side' => $side = mt_rand(1, 2)];
        $list[] = ['id' => array_slice($items, $mode, 1)[0]['id'], 'side' => $side == 1 ? 2 : 1];

        $rand_arr = range(0, $mode - 2);
        shuffle($rand_arr);
        foreach ($rand_arr as $k => $v) {
            $side   = $k % 2 ? ($side == 1 ? 2 : 1) : mt_rand(1, 2);
            $list[] = ['id' => array_slice($items, $v, 1)[0]['id'], 'side' => $side];
            $list[] = ['id' => array_slice($items, $mode * 2 - $v - 1, 1)[0]['id'], 'side' => $side];
        }

        halt($list);

        // $mode = count($items) / 2;
        // $list[] = ['id' => array_slice($items, $mode - 1, 1)[0]['id'], 'side' => $side = mt_rand(1, 2)];
        // $list[] = ['id' => array_slice($items, $mode, 1)[0]['id'], 'side' => $side == 1 ? 2 : 1];

        // $rand_arr = range(0, $mode - 2);
        // shuffle($rand_arr);
        // foreach ($rand_arr as $v) {
        //     $side   = $v % 2 ? ($side == 1 ? 2 : 1) : mt_rand(1, 2);
        //     $list[] = ['id' => array_slice($items, $v, 1)[0]['id'], 'side' => $side];
        //     $list[] = ['id' => array_slice($items, $mode * 2 - $v - 1, 1)[0]['id'], 'side' => $side];
        // }

        // $num = count($items) / 2 - 1;
        // for ($i = 0; $i < $num; $i++) {
        //     $side   = $i % 2 ? ($side == 1 ? 2 : 1) : mt_rand(1, 2);
        //     $list[] = ['id' => array_shift($items)['id'], 'side' => $side];
        //     $list[] = ['id' => array_pop($items)['id'], 'side' => $side];
        // }

        // $list[] = ['id' => array_shift($items)['id'], 'side' => $side = mt_rand(1, 2)];
        // $list[] = ['id' => array_pop($items)['id'], 'side' => $side == 1 ? 2 : 1];

        // halt($list);

    }

    protected function chkResult($id)
    {
        $round        = model('yue_round');
        $round_member = model('yue_round_member');
        $this_round   = $round->find($id);
        $finished_num = $round_member->where('rid', $id)->count();
        $items        = $finished_num;
        $is_over      = $finished_num >= $this_round->mode * 2;

        if ($is_over) {
            // $ramdon_arr = range(1, $this_round->mode * 2);
            // shuffle($ramdon_arr);
            // $items = $round_member->where('rid', $id)->select();
            $items = Db::view('yue_member', 'id')
                ->view('yue_round_member', 'id', 'yue_member.id = yue_round_member.uid')
                ->where(['yue_round_member.rid' => $id])
                ->order('yue_member.rank, yue_member.score')
                ->select();

            // trace('items:'.json_encode($items, true), 'error');
            // foreach ($items as $key => $item) {
            //     if (!($key % 2)) {
            //         $side = mt_rand(1, 2);
            //     } else {
            //         $side = $side == 1 ? 2 : 1;
            //     }
            //     $list[] = ['id' => $item['id'], 'side' => $side];
            // }
            // $num = count($items) / 2 - 1;
            // for ($i = 0; $i < $num; $i++) {
            //     $side   = $i % 2 ? ($side == 1 ? 2 : 1) : mt_rand(1, 2);
            //     $list[] = ['id' => array_shift($items)['id'], 'side' => $side];
            //     $list[] = ['id' => array_pop($items)['id'], 'side' => $side];
            // }

            // $list[] = ['id' => array_shift($items)['id'], 'side' => $side = mt_rand(1, 2)];
            // $list[] = ['id' => array_pop($items)['id'], 'side' => $side == 1 ? 2 : 1];

            $mode   = count($items) / 2;
            $list[] = ['id' => array_slice($items, $mode - 1, 1)[0]['id'], 'side' => $side = mt_rand(1, 2)];
            $list[] = ['id' => array_slice($items, $mode, 1)[0]['id'], 'side' => $side == 1 ? 2 : 1];

            $rand_arr = range(0, $mode - 2);
            shuffle($rand_arr);
            foreach ($rand_arr as $k => $v) {
                $side   = $k % 2 ? ($side == 1 ? 2 : 1) : mt_rand(1, 2);
                $list[] = ['id' => array_slice($items, $v, 1)[0]['id'], 'side' => $side];
                $list[] = ['id' => array_slice($items, $mode * 2 - $v - 1, 1)[0]['id'], 'side' => $side];
            }

            $round_member->saveAll($list);

            $items = $round_member->where('rid', $id)->order('side')->select();
            // if ($this_round->status == 1) {
            //     if ($this_round->cash > 0) {
            //         $pay = $this->getWechatPay();
            //         $total_cash = $this_round->set_fee * $this_round->mode * 2 * 100;
            //         $result = $pay->transfers($this_round->openid, $total_cash, self::getBillno(), '押金退回');
            //         trace($pay->errMsg, 'error');
            //         $result and $this_round->save(['status' => 2]);
            //     } else {
            //         $this_round->save(['status' => 2]);
            //     }
            // }

            if ($this_round->status == 1) {
                $this_round->save(['status' => 2]);
            }
        }

        Gateway::sendToGroup($id, \json_encode(['type' => 'update', 'is_over' => $is_over, 'items' => $items]));

        if ($is_over) {
            $time = date('Y/m/d H:i:s');
            $cash = $this_round->cash;
            foreach ($items as $v) {
                $side = $v['side'] == 1 ? '上队' : '下队';
                $this->sendNotice($id, $v['openid'], [
                    'name' => '王者荣耀(' . $side . ')',
                    'time' => $time,
                    'cash' => $cash . '元',
                    'note' => '尊敬的约战堂玩家，随机分边你被分为' . $side . '，请立即进入游戏接受其他玩家挑战吧！游戏结束后，防跑路报名费将由创建者退还。欢迎再次使用约战堂，创建者可以获得房费的一半作为推荐和组织奖励！祝您游戏愉快！',
                ]);
            }
        }
    }

    protected function sendNotice($rid, $openid, $data)
    {
        if (!$formid = $this->getFormId($openid)) {
            return;
        }

        $info = [
            'touser'           => $openid,
            'template_id'      => 'OanDtZoSWPSSNntKfcOHg9GPqoE4Cl0gGUQHlfg2jMo',
            'page'             => 'pages/demo/demo?id=' . $rid,
            'form_id'          => $formid,
            'data'             => [
                'keyword1' => [
                    'value' => $data['name'],
                    'color' => '#173177',
                ],
                'keyword2' => [
                    'value' => $data['time'],
                    // 'color' => '#173177',
                ],
                'keyword3' => [
                    'value' => $data['cash'],
                    // 'color' => '#173177',
                ],
                'keyword4' => [
                    'value' => $data['note'],
                    'color' => '#173177',
                ],
            ],
            'emphasis_keyword' => 'keyword1.DATA',
        ];

        $access_token = $this->getAccessToken();
        // $client = new Client();
        // $res = $client->request('POST', "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$access_token}", $info);
        $res = self::curl("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$access_token}", $info);
        trace($res, 'error');
        return $res;
    }

    protected static function curl($url, $data = '')
    {
        $ch      = curl_init();
        $timeout = 300;
        curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_REFERER, "http://www.111cn.net/"); // 伪装来路
        $data and curl_setopt($ch, CURLOPT_POST, 1);
        $data and curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // URL为SSL时添加这行可解决页面空白
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    protected function addFormId($openid, $formid)
    {
        $openid      = $this->appid . $openid;
        $formid_list = cache($openid);
        if (\is_array($formid_list)) {
            $formid_list[] = $formid;
        } else {
            $formid_list = [$formid];
        }

        return cache($openid, $formid_list, 86400);
    }

    protected function getFormId($openid)
    {
        $openid      = $this->appid . $openid;
        $formid_list = cache($openid);
        if (is_array($formid_list) and count($formid_list) >= 1) {
            $res = array_pop($formid_list);
            cache($openid, $formid_list);
            return $res;
        }
        return false;
    }

    protected static function getBillno()
    {
        return time() . mt_rand(100000, 999999);
    }

    protected function getWechatPay()
    {
        \Wechat\Loader::config($this->options);
        return $pay = new \Wechat\WechatPay();
    }

    protected function getAccessToken()
    {
        if ($access_token = cache($this->appid . 'access_token')) {
            return $access_token;
        }

        $res = self::curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}");
        $res = json_decode($res, true);
        // {"access_token": "ACCESS_TOKEN", "expires_in": 7200}
        cache($this->appid . 'access_token', $res['access_token'], $res['expires_in'] - 200);
        return $res['access_token'];
    }
}
